#include <stdio.h>

#ifndef MAX
#define MAX 50001
#endif

int f[MAX], r[MAX];

/**************************************
* Funciont Name: init_set
* Params: void
* Return: int
* Description: 
**************************************/

int init_set (void)
{

    int i;
    for (i = 0; i < MAX; i++) {
        f[i] = i;
    }

    return 0;
}

/**************************************
* Funciont Name: find_set
* Params: int x
* Return: int
* Description: 
**************************************/

int find_set (int x)
{
    int t;

    if (f[x] == x) {
        return x;
    } else {
        t = f[x];
        f[x] = find_set(f[x]);

        r[x] = (r[t] + r[x]) % 3;
    }

    return f[x];
}

/**************************************
* Funciont Name: union_set
* Params: int x, int y, int len
* Return: int
* Description: 
**************************************/

int union_set (int x, int y, int len)
{

    int a = find_set(x);
    int b = find_set(y);

    f[a] = b;
    r[a] = (r[y] - r[x] + 3 + len) % 3;

    return 0;
}

int main (int argc, char const* argv[])
{

    int n, m;
    int d, x, y;
    int rx, ry;
    int sum = 0;
    scanf("%d %d", &n, &m);
    init_set();

    while (m--) {
        scanf("%d %d %d", &d, &x, &y);

        /*x，y比n大，越界；x吃自己*/
        if (x > n || y > n || (d == 2 && x == y)) {
            sum ++;
        } else {
            rx = find_set(x);
            ry = find_set(y);

            if (rx == ry) {
                if ((r[x] - r[y] + 3) % 3 != d - 1) {
                    sum ++;
                }
            } else {
                union_set(x, y, d - 1);
            }
        }
    }
    printf("%d\n", sum);

    return 0;
}
